package converter

import (
	"bytes"
	"log"
	"os/exec"
	"path/filepath"
)

func init() {
	Register(M4S, "m4s", M4sConverter)
}

func M4sConverter(cacheVideoDir *CacheVideoDir, targetPath, temp string) {
	path := filepath.Join(targetPath, cacheVideoDir.Title)
	if len(cacheVideoDir.FileInfo) == 0 || !MkdirAllDir(path) {
		return
	}
	videoName := ""
	for _, videoInfo := range cacheVideoDir.FileInfo {
		if len(videoInfo.Videos) != 2 {
			continue
		}
		videoName = filepath.Join(path, videoInfo.Title)
		videoName = videoName + videoInfo.Suffix
		invokeM4s(videoName, videoInfo.Videos)
	}
}

func invokeM4s(videoName string, video []string) {
	var stdout bytes.Buffer
	var stderr bytes.Buffer
	cmd := exec.Command("ffmpeg", "-i", video[0], "-i", video[1], "-codec", "copy", videoName)
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr
	err := cmd.Run()
	if err != nil {
		log.Println("执行命令失败:", err.Error())
		log.Println("--- stdout ---")
		log.Println(stdout.String())
		log.Println("--- stderr ---")
		log.Println(stderr.String())
		return
	}
}
